<?php
namespace App\Common;


use App\Api\Controllers\Config\WeixinConfigController;
use App\Api\Controllers\Device\YlianyunAopClient;
use App\Api\Controllers\Device\ZlbzController;
use App\Api\Controllers\Push\JpushController;
use App\Api\Controllers\Qmtt\AliBaseController;
use App\Jobs\CzUpdateStatus;
use App\Models\Device;
use App\Models\MqttConfig;
use App\Models\VConfig;
use App\Models\WeixinNotify;
use App\Models\WeixinNotifyTemplate;
use App\Services\Pay\PayService;
use App\Util\LockUtil;
use EasyWeChat\Factory;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use karpy47\PhpMqttClient\MQTTClient;
use MyBank\Tools;
use Illuminate\Support\Facades\Log;
use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Iotcloud\V20180614\IotcloudClient;
use TencentCloud\Iotcloud\V20180614\Models\PublishMessageRequest;

class PaySuccessAction
{
    //支付成功以后的操作
    public static function action($data)
    {
        try {
            if(isset($data["out_trade_no"])){
                $isRun=LockUtil::lock("out_trade_no_" . $data["out_trade_no"]);
                if(empty($isRun)){
                    return ;
                }
                //设置成功设置过期时间
//                LockUtil::expire("out_trade_no_" . $data["out_trade_no"]);
            }
            //AMQP支付
            PayService::payOkHandle($data);
            self::action_tb($data);
            try {
                (new \App\Api\Controllers\User\CompanyController())->updateTotalAmount($data);
            } catch (\Exception $e) {

            }
        } catch (\Exception $ex) {
            \Illuminate\Support\Facades\Log::info('支付成功后error');
            \Illuminate\Support\Facades\Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
        } finally {
            if(isset($data["out_trade_no"])){
                LockUtil::unLock("out_trade_no_" . $data["out_trade_no"]);
            }
        }
    }


    //同步操作数据库
    public static function action_tb($data)
    {	
        $push_action = 'tb';
        $count_action = "tb";
        $user_money = "tb";//
        $fuwu = "tb";//
        $member = "tb";//
        $member_cz = "tb";//
        $merchant_money = "tb";//

        $QUEUE_DRIVER = Cache::remember('QUEUE_DRIVER', 1000, function () {
            $QUEUE_DRIVER = env('QUEUE_DRIVER');
            return $QUEUE_DRIVER;
        });

        if ($QUEUE_DRIVER == "redis") {
            //2.统计
            $count_action = "yb";
            //3.返佣
            $user_money = "yb";
            //4.服务
            $fuwu = "yb";
            //8会员
            $member = "tb";
            //9.充值
            $member_cz = "tb";
            //10 商户返佣
            $merchant_money = "yb";
        }

        //8.会员
        try {
            if ($member == "tb") {
                $obj = new AddMember($data);
                $obj->insert();
            } else {
                dispatch(new \App\Jobs\AddMember($data));
            }
        } catch (\Exception $ex) {
            \Illuminate\Support\Facades\Log::info('8.会员error');
            \Illuminate\Support\Facades\Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
        }

        //9.充值订单处理
        if (isset($data['device_id']) && $data['device_id'] == 'member_cz') {
            try {
                if ($member_cz == "tb") {
                    $obj = new \App\Common\CzUpdateStatus($data);
                    $obj->insert();
                } else {
                    dispatch(new \App\Jobs\CzUpdateStatus($data));
                }
            } catch (\Exception $ex) {
                \Illuminate\Support\Facades\Log::info('会员充值状态同步error');
                \Illuminate\Support\Facades\Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
            }
        }

        try {
            //主扫不播报
            if (strpos($data['out_trade_no'], 'scan')) {
                $data['no_push'] = 1;
            }

            //不播报
            if (isset($data['no_push'])) {
                //不播报
            } else {
                //1.安卓app语音播报
                if ($push_action == "tb") {
                    $jpush = new JpushController();
                    $jpush->push($data['ways_type_desc'], $data['total_amount'], $data['out_trade_no'], $data['merchant_id'], $data['store_id'], $data['config_id']);
                } else {
                    //  dispatch(new \App\Jobs\PayJpush($data['ways_type_desc'], $data['total_amount'], $data['out_trade_no'], $data['merchant_id'], $data['store_id'], $data['config_id']));
                }
            }
        } catch (\Exception $ex) {
            \Illuminate\Support\Facades\Log::info('安卓app语音播报error');
            \Illuminate\Support\Facades\Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
        }

        //2.统计
        try {
            if (isset($data['no_count'])) {

            } else {
                $fee_amount = isset($data['fee_amount']) && $data['fee_amount'] ? $data['fee_amount'] : $data['rate'] * $data['total_amount'];
                $fee_amount = number_format($fee_amount, 4, '.', '');
                $data['fee_amount'] = $fee_amount;
                if ($count_action == "tb") {
                    StoreDayMonthOrder::insert($data);
                } else {
                    //队列
                    dispatch(new \App\Jobs\StoreDayMonthOrder($data));
                }
            }
        } catch (\Exception $ex) {
            \Illuminate\Support\Facades\Log::info('2.统计error');
            \Illuminate\Support\Facades\Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
        }

        //3.服务商返佣
        try {
            if (isset($data['no_user_money'])) {

            } else {
                if ($user_money == "tb") {
                    $UserGetMoney = [
                        'config_id' => $data['config_id'],//服务商ID
                        'user_id' => $data['user_id'],//直属代理商
                        'store_id' => $data['store_id'],//门店
                        'out_trade_no' => $data['out_trade_no'],//订单号
                        'ways_type' => $data['ways_type'],//通道类型
                        'order_total_amount' => $data['total_amount'],//交易金额
                        'store_ways_type_rate' => $data['rate'],//交易时的费率
                        'source_type' => $data['source_type'],//返佣来源
                        'source_desc' => $data['source_desc'],//返佣来源说明
                    ];
                    $obj = new  UserGetMoney($UserGetMoney);
                    $obj->insert();
                } else {
                    //队列
                    $UserGetMoney = [
                        'config_id' => $data['config_id'],//服务商ID
                        'user_id' => $data['user_id'],//直属代理商
                        'store_id' => $data['store_id'],//门店
                        'out_trade_no' => $data['out_trade_no'],//订单号
                        'ways_type' => $data['ways_type'],//通道类型
                        'order_total_amount' => $data['total_amount'],//交易金额
                        'store_ways_type_rate' => $data['rate'],//交易时的费率
                        'source_type' => $data['source_type'],//返佣来源
                        'source_desc' => $data['source_desc'],//返佣来源说明
                    ];
                    dispatch(new \App\Jobs\UserGetMoney($UserGetMoney));
                }
            }
        } catch (\Exception $ex) {
            \Illuminate\Support\Facades\Log::info('3.服务商返佣error');
            \Illuminate\Support\Facades\Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
        }

        //4.服务
        try {
            if (isset($data['no_fuwu'])) {

            } else {
                if ($fuwu == "tb") {
                    //   $title = $data['ways_type_desc'] . '到账' . $data['total_amount'] . '元';
                    //   MerchantFuwu::insert($title, $data['ways_type_desc'], $data['store_id'], $data['merchant_id'], $data['total_amount'], $data['out_trade_no']);
                } else {
                    //  $title = $data['ways_type_desc'] . '到账' . $data['total_amount'] . '元';
                    //  dispatch(new \App\Jobs\MerchantFuwu($title, $data['ways_type_desc'], $data['store_id'], $data['merchant_id'], $data['total_amount'], $data['out_trade_no']));
                }
            }
        } catch (\Exception $ex) {
            \Illuminate\Support\Facades\Log::info('4服务error');
            \Illuminate\Support\Facades\Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
        }

        //5.微信公众号消息提醒
        try {
            if (isset($data['no_wx'])) {

            } else {
                self::weixin_notify($data);
            }
        } catch (\Exception $ex) {
            \Illuminate\Support\Facades\Log::info('5微信公众号消息提醒error');
            \Illuminate\Support\Facades\Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
        }

        //6.打印
        try {
            if (isset($data['store_id']) && $data['store_id'] == '2023012914242355846') {
                file_put_contents('feie.log',var_export($data,true)."\r\n",FILE_APPEND);
            }
            //file_put_contents('feie.log',var_export($data,true)."\r\n",FILE_APPEND);
            if (isset($data['no_print'])) {
                //不打印
            } else {
                if (isset($data['remark'])) {

                } else {
                    $data['remark'] = '备注';
                }
                self::print_data($data);
            }
        } catch (\Exception $ex) {
            \Illuminate\Support\Facades\Log::info('打印error');
            \Illuminate\Support\Facades\Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
        }
        //7.播报
        try {
            if (isset($data['no_v'])) {
                //不播报
            } else {
                //1 支付宝 2 微信支付 3京东支付 4 银联闪付  5 积分抵扣  6.会员卡
                $type = '0';
                if ($data['ways_source'] == "alipay") {
                    $type = '1';
                }

                if ($data['ways_source'] == "weixin") {
                    $type = '2';
                }
                if ($data['ways_source'] == "unionpay") {
                    $type = '4';
                }

                if ($data['ways_source'] == "member") {
                    $type = '6';
                }

                $device_id = isset($data['device_id']) ? $data['device_id'] : "";

                self::v_send($data['total_amount'] * 100, $data['store_id'], $type, $data['merchant_id'], $data['config_id'], $data['out_trade_no'], $device_id);
            }
        } catch (\Exception $ex) {
            \Illuminate\Support\Facades\Log::info('播报error');
            \Illuminate\Support\Facades\Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
        }

        //3.商户返佣
        try {
            if (isset($data['no_merchant_money'])) {

            } else {
                if ($merchant_money == "tb") {
                    $MerchantGetMoney = [
                        'config_id' => $data['config_id'], //服务商ID
                        'user_id' => $data['user_id'], //直属代理商
                        'store_id' => $data['store_id'], //门店
                        'out_trade_no' => $data['out_trade_no'], //订单号
                        'ways_type' => $data['ways_type'], //通道类型
                        'order_total_amount' => $data['total_amount'], //交易金额
                        'store_ways_type_rate' => $data['rate'], //交易时的费率
                        'source_type' => $data['source_type'], //返佣来源
                        'source_desc' => $data['source_desc'], //返佣来源说明
                        'company' => $data['company'], //
                        'ways_source' => $data['ways_source'], //
                    ];

                    $obj = new  MerchantGetMoney($MerchantGetMoney);
                    $obj->insert();
                } else {
                    //队列
                    $MerchantGetMoney = [
                        'config_id' => $data['config_id'], //服务商ID
                        'user_id' => $data['user_id'], //直属代理商
                        'store_id' => $data['store_id'], //门店
                        'out_trade_no' => $data['out_trade_no'], //订单号
                        'ways_type' => $data['ways_type'], //通道类型
                        'order_total_amount' => $data['total_amount'], //交易金额
                        'store_ways_type_rate' => $data['rate'], //交易时的费率
                        'source_type' => $data['source_type'], //返佣来源
                        'source_desc' => $data['source_desc'], //返佣来源说明
                        'company' => $data['company'], //
                        'ways_source' => $data['ways_source'], //
                    ];
                    dispatch(new \App\Jobs\MerchantGetMoney($MerchantGetMoney));
                }
            }
        } catch (\Exception $ex) {
            \Illuminate\Support\Facades\Log::info('商户返佣error');
            \Illuminate\Support\Facades\Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
        }
    }


    //微信公众号消息提醒
    public static function weixin_notify($data)
    {
        try {
            //判断服务商是否有设置模版消息
            $config_id = $data['config_id'];
            $config = new WeixinConfigController();
            $config_obj = $config->weixin_config_obj($config_id);

            if ($config_obj) {
                $config = [
                    'app_id' => $config_obj->wx_notify_appid,
                    'secret' => $config_obj->wx_notify_secret,
                ];

                //有收银员，推送给收银员和店长
                   
         
                if (isset($data['merchant_id']) && !empty($data['merchant_id'])) {
                    $WeixinNotify = WeixinNotify::where('merchant_id', $data['merchant_id'])
                        ->where('store_id', $data['store_id'])
                        ->select('wx_open_id')
                        ->first();
                    if ($WeixinNotify) {
                        $app = Factory::officialAccount($config);
                        $app->template_message->send([
                            'touser' => $WeixinNotify->wx_open_id,
                            'template_id' => $config_obj->template_id,
                            'url' => url('/mb/login'),
                            'data' => [
                                'first' => '门店名称:' . $data['store_name'],
                                'keyword1' => $data['total_amount'] . '元',
                                'keyword2' => $data['ways_type_desc'],
                                'keyword3' => date('Y-m-d H:i:s', time()),
                                'keyword4' => $data['out_trade_no'],
                                'remark' => ''
                            ]
                        ]);
                    }

                    $managerNotify = DB::table('weixin_notifys as wn')
                        ->select(['wn.store_id', 'wn.merchant_id', 'wn.wx_open_id'])
                        ->join('merchant_stores as ms', function($join) {
                            $join->on('wn.store_id', '=', 'ms.store_id')
                                ->on('wn.merchant_id', '=', 'ms.merchant_id')
                                ->where('ms.type', '=', '1');
                        })
                        ->join('merchants as m', function($join2) {
                            $join2->on('m.id', '=', 'wn.merchant_id')
                                ->where('m.type', '=', '1');
                        })
                        ->where('wn.merchant_id', '<>', $data['merchant_id'])
                        ->where('wn.store_id', $data['store_id'])
                        ->get();
                        
                    if ($managerNotify) {
                        foreach ($managerNotify as $key => $values) {
                            if ($values->wx_open_id) {
                                $app = Factory::officialAccount($config);
                                $app->template_message->send([
                                    'touser' => $values->wx_open_id,
                                    'template_id' => $config_obj->template_id,
                                    'url' => url('/mb/login'),
                                    'data' => [
                                        'first' => '门店名称:' . $data['store_name'],
                                        'keyword1' => $data['total_amount'] . '元',
                                        'keyword2' => $data['ways_type_desc'],
                                        'keyword3' => date('Y-m-d H:i:s', time()),
                                        'keyword4' => $data['out_trade_no'],
                                        'remark' => ''
                                    ],
                                ]);
                            }
                        }
                    }

                } else {
                    $WeixinNotify = WeixinNotify::where('store_id', $data['store_id'])
                        ->select('wx_open_id')
                        ->get();
                    if ($WeixinNotify) {
                        foreach ($WeixinNotify as $k => $v) {
                            $app = Factory::officialAccount($config);
                            $app->template_message->send([
                                'touser' => $v->wx_open_id,
                                'template_id' => $config_obj->template_id,
                                'url' => url('/mb/login'),
                                'data' => [
                                    'first' => '门店名称:' . $data['store_name'],
                                    'keyword1' => $data['total_amount'] . '元',
                                    'keyword2' => $data['ways_type_desc'],
                                    'keyword3' => date('Y-m-d H:i:s', time()),
                                    'keyword4' => $data['out_trade_no'],
                                    'remark' => ''
                                ],
                            ]);
                        }
                    }
                }
            }

        } catch (\Exception $ex) {
            \Illuminate\Support\Facades\Log::info('微信公众号消息提醒error');
            \Illuminate\Support\Facades\Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
        }
    }


    //打印
    public static function print_data($data)
    {
        try {
            $p = Device::where('store_id', $data['store_id'])
                ->where('merchant_id', $data['merchant_id'])
                ->where("type", "p")
                ->get();
//file_put_contents('feie.log',var_export($p,true)."\r\n",FILE_APPEND);
            //收银员未绑定走门店机器
            if ($p->isEmpty()) {
                $p = Device::where('store_id', $data['store_id'])
                    ->where('merchant_id', '')
                    ->where("type", "p")
                    ->get();
            }

            if (!$p->isEmpty()) {
                foreach ($p as $v) {
                    //智联
                    if ($v->device_type == "p_zlbz_1") {
                        $da = new ZlbzController();
                        $store_name = $data['store_name'];
                        $order_no = '' . $data['out_trade_no'] . '';
                        $price = '' . $data['total_amount'] . '';
                        $remark = '' . $data['remark'] . '';
                        $qr_url = 'https:www';
                        $type = $data['ways_type_desc'];
                        try {
                            $device_id = $v->device_no;
                            $da->print_send($device_id, $type, $store_name, $order_no, $price, $remark, $qr_url);
                        } catch (\Exception $exception) {
                            \Illuminate\Support\Facades\Log::info($exception);
                            continue;
                        }
                    }
                    
                    //飞鹅云
                    if ($v->device_type == "p_fey") {
                        $da = new ZlbzController();
                        $store_name = $data['store_name'];
                        $order_no = '' . $data['out_trade_no'] . '';
                        $price = '' . $data['total_amount'] . '';
                        $remark = '' . $data['remark'] . '';
                        $qr_url = 'https:www';
                        $type = $data['ways_type_desc'];
                        try {
                            $merchants=DB::table('merchants')->where('id',$data['merchant_id'])->select('name')->first();
                            $content = '<CB>付款回执</CB><BR>';
                            $content .= '--------------------------------<BR><BR>';
                            $content .= "商户名称:".$store_name."<BR><BR>";
                            $content .= "交易时间:".'1234'."<BR><BR>";
                            $content .= "皖付通订单号:".$order_no."<BR><BR>";
                            $content .= "原始订单号：".$order_no."<BR><BR>";
                            $content .= "付款方式：".$data['source_desc']."<BR><BR>";
                            $content .= "款台名称：".$merchants->name."<BR><BR>";
                            $content .= "流水号：".$order_no."<BR><BR>";
                            $content .= "合计：".$price."元<BR>";
                            $content .= '--------------------------------<BR><BR>';
                            $content .= '签名：<BR><BR><BR>';
                            $content .= '<C>谢谢惠顾,欢迎下次光临</C>';
                            $time=time();
                            $msgInfo = array(
                              'user'=>'215496618@qq.com',
                              'stime'=>$time,
                              'sig'=>sha1('215496618@qq.com'.'gLYHT9s2NwAjp9KV'.$time),
                              'apiname'=>'Open_printMsg',
                              'sn'=>$v->device_no,
                              'content'=>$content
                            );
                            $querystring = '';
                            if (is_array($msgInfo)) {
                                foreach ($msgInfo as $key => $val) {
                                    if (is_array($val)) {
                                        foreach ($val as $val2) {
                                            $querystring .= urlencode($key).'='.urlencode($val2).'&';
                                        }
                                    } else {
                                        $querystring .= urlencode($key).'='.urlencode($val).'&';
                                    }
                                }
                                $querystring = substr($querystring, 0, -1); // Eliminate unnecessary &
                            } else {
                                $querystring = $msgInfo;
                            }
                            $curl = curl_init();
                            curl_setopt($curl, CURLOPT_URL, 'https://api.feieyun.cn/Api/Open/');
                            curl_setopt($curl, CURLOPT_HEADER, 0);//不抓取头部信息。只返回数据
                            curl_setopt($curl, CURLOPT_TIMEOUT, (int)5000);//超时设置
                            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//1表示不返回bool值
                            curl_setopt($curl, CURLOPT_POST, 1);
                            curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));//重点
                            curl_setopt($curl, CURLOPT_POSTFIELDS, $querystring);
                            $res = curl_exec($curl);
                            file_put_contents('feie.log',var_export($data['store_id'],true)."\r\n",FILE_APPEND);
                            file_put_contents('feie.log',var_export($res,true)."\r\n",FILE_APPEND);
                        } catch (\Exception $exception) {
                            \Illuminate\Support\Facades\Log::info($exception);
                            continue;
                        }
                    }
                    
                    //K4
                    if ($v->device_type == "p_yly_k4") {
                        $VConfig = VConfig::where('config_id', $v->config_id)
                            ->select(
                                'yly_user_id',
                                'yly_api_key'
                            )->first();
                        if (!$VConfig) {
                            $VConfig = VConfig::where('config_id', '1234')
                                ->select(
                                    'yly_user_id',
                                    'yly_api_key'
                                )->first();
                        }
                        if (!$VConfig) {
                            \Illuminate\Support\Facades\Log::info('易联云打印未配置app/common/PaySuccessAction.php');
                            continue;
                        }

                        try {
                            $da = new YlianyunAopClient();
                            $push_id = $VConfig->yly_user_id; //用户id
                            $push_key = $VConfig->yly_api_key; //api密钥
                            $data['device_key'] = $v->device_key;
                            $data['device_no'] = $v->device_no;
                            $data['push_id'] = $push_id;
                            $data['push_key'] = $push_key;
                            $data['type'] = $data['ways_type_desc'];
                            $da->send_print($data);
                        } catch (\Exception $exception) {
                            \Illuminate\Support\Facades\Log::info('易联云打印');
                            \Illuminate\Support\Facades\Log::info($exception);
                            continue;
                        }
                    }
                }
            }
        } catch (\Exception $ex) {
            \Illuminate\Support\Facades\Log::info('打印error');
            \Illuminate\Support\Facades\Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
        }
    }


    //播报设备 金额是分
    public static function v_send($price, $store_id, $type, $merchant_id, $config_id = "1234", $out_trade_no, $device_id = "")
    {
        try {
            //error_log(date('Y-m-d H:i:s')." 【联迪云喇叭-error】： ".json_encode([$merchant_id])."\n\n", 3, "/tmp/". 'landi'.date('Ymd').".log");
            //设备播报
            if ($merchant_id && (int)$merchant_id != 0) {
                $Device = Device::where('store_id', $store_id)
                    ->where('merchant_id', $merchant_id)
                    ->whereIn("device_type", ["v_bp_1", 'v_jbp_d30', 'v_kd_58', 'v_zw_1', 's_bp_sl51', 's_bp_sl56',
                        'v_zlbz_1', 's_ky_mp10','v_ps_sp08','phone', 'v_cls_q038','v_car_CG02','v_whty','v_whty_1', 'v_ld_ns20', 'csyz_YZ07'])
                    ->get();
            } else {
                $Device = Device::where('store_id', $store_id)
                    //->where('merchant_id', '')
                    ->whereIn("device_type", ["v_bp_1", 'v_jbp_d30', 'v_kd_58', 'v_zw_1', 's_bp_sl51', 's_bp_sl56',
                        'v_zlbz_1', 's_ky_mp10','v_ps_sp08', 'phone', 'v_cls_q038','v_car_CG02','v_whty','v_whty_1', 'v_ld_ns20', 'csyz_YZ07'])
                    ->get();
            }

            if ($Device->isEmpty()) {
					
            } else {
                foreach ($Device as $k => $v) {
                    //智联博众
                    if ($v->device_type == "v_zlbz_1") {
                        $VConfig = VConfig::where('config_id', $config_id)
                            ->select('zlbz_token')->first();

                        if (!$VConfig) {
                            $VConfig = VConfig::where('config_id', '1234')
                                ->select(
                                    'zlbz_token'
                                )->first();
                        }

                        $datap = [
                            'id' => $v->device_no,
                            'price' => $price,
                            'uid' => $store_id,
                            'token' => $VConfig->zlbz_token,
                            'pt' => $type
                        ];

                        //  Tools::curl($datap, 'http://39.106.131.149/add.php');
                    }

                    //智网
                    if ($v->device_type == "v_zw_1") {
                        $VConfig = VConfig::where('config_id', $config_id)
                            ->select(
                                'zw_token'
                            )->first();
                        if (!$VConfig) {
                            $VConfig = VConfig::where('config_id', '1234')
                                ->select(
                                    'zw_token'
                                )->first();
                        }
                        $url = 'http://cloudspeaker.smartlinkall.com/add.php?token=' . $VConfig->zw_token . '&id=' . $v->device_no . '&uid=' . $store_id . $v->device_no . '&seq=' . time() . '&price=' . $price . '&pt=' . $type . '&vol=100';
                        $data = Tools::curl_get($url);

                        //老的智网喇叭配置
                        $oldVConfig = VConfig::where('config_id', $config_id)
                            ->select('old_zw_token')
                            ->first();
                        if (!$oldVConfig) {
                            $oldVConfig = VConfig::where('config_id', '1234')
                                ->select('old_zw_token')
                                ->first();
                        }
                        if ($oldVConfig) {
                            $url = 'http://cloudspeaker.smartlinkall.com/add.php?token=' . $oldVConfig->old_zw_token . '&id=' . $v->device_no . '&uid=' . $store_id . $v->device_no . '&seq=' . time() . '&price=' . $price . '&pt=' . $type . '&vol=100';
                            $data = Tools::curl_get($url);
                        }
                    }

                    //推送卡台小喇叭+波谱sl51
                    if (in_array($v->device_type, ['v_bp_1', 'v_jbp_d30', 'v_kd_58', 's_bp_sl51', 's_bp_sl56', 's_ky_mp10','v_ps_sp08','phone'])) {
                        $type_desc = "";
                        //1 支付宝 2 微信支付 3京东支付 4 银联闪付  5 积分抵扣  6.会员卡
                        if ($type == '1') {
                            $type_desc = "支付宝";
                        }
                        if ($type == '2') {
                            $type_desc = "微信";
                        }

                        if ($type == '3') {
                            $type_desc = "京东";
                        }
                        if ($type == '4') {
                            $type_desc = "银联云闪付";
                        }

                        if ($type == '5') {
                            $type_desc = "积分抵扣";
                        }

                        if ($type == '6') {
                            $type_desc = "会员卡";
                        }

                        //反扫推送类型的设备不播报
                        if (in_array($v->device_type, ['s_bp_sl51', 's_bp_sl56']) && strpos($out_trade_no, 'scan')) {

                        } else {
                            $message = $type_desc . '支付' . ($price / 100) . '元';
                            $orderNum = date('YmdHis', time()) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999));
                            self::mqtt($v->device_no, $v->device_type, $message, $orderNum, $config_id, $type, $price);
                        }
                    }				
					
					
					// 畅立收Q038
                    if ($v->device_type == "v_cls_q038") {
                        $VConfig = VConfig::where('config_id', $config_id)
                            ->select(
                                'tencent_cloud_secretid',
                                'tencent_cloud_secretkey',
                                'cls_product_id',
                                'cls_prefix'
                            )->first();
                        if (!$VConfig) {
                            $VConfig = VConfig::where('config_id', '1234')
                                ->select(
                                    'tencent_cloud_secretid',
                                    'tencent_cloud_secretkey',
                                    'cls_product_id',
                                    'cls_prefix'
                                )->first();
                        }

                        $secretId = $VConfig->tencent_cloud_secretid;
                        $secretKey = $VConfig->tencent_cloud_secretkey;
                        $productId = $VConfig->cls_product_id;
                        $deviceName = $v->device_no;
                        $money = ($price / 100);
                        // $msg = $VConfig->cls_prefix . $money .'元';
                        $msg = $VConfig->cls_prefix . $money .'元';
                        $channel = 0;
                        $msgid = $store_id . date('YmdHis', time());

                        try {
                            $cred = new Credential($secretId, $secretKey);
                            $httpProfile = new HttpProfile();
                            $httpProfile->setEndpoint("iotcloud.tencentcloudapi.com");

                            $clientProfile = new ClientProfile();
                            $clientProfile->setHttpProfile($httpProfile);
                            $client = new IotcloudClient($cred, "", $clientProfile);

                            $req = new PublishMessageRequest();

                            $params = array(
                                "Topic" => $productId . '/' . $deviceName . '/data',
                                "Payload" => "{\"msg\":\"$msg\",\"channel\":$channel,\"money\":\"$money\",\"msgid\":\"$msgid\"}",
                                "ProductId" => $productId,
                                "DeviceName" => $deviceName
                            );
                            $req->fromJsonString(json_encode($params));

                            $client->PublishMessage($req);
                        }
                        catch(TencentCloudSDKException $e) {
                            Log::info("畅立收播报出错");
                            Log::info($e->getMessage().' | '.$e->getFile().' | '.$e->getLine());
                        }
                    }

                    // 云想印CG02
                    if ($v->device_type == "v_car_CG02") {
                        $deviceName = $v->device_no;
                        $money = ($price / 100);
                        if ($type == '1') {
                            $broadCastType = 3;
                        }
                        if ($type == '2') {
                            $broadCastType = 2;
                        }
                        if ($type == '4') {
                            $broadCastType = 8;
                        }
                        try {
                            $out_order_id=$out_trade_no;
                            $params=array(
                                'appId'=>'ZF441',
                                'timestamp'=>time().'000',
                                'requestId'=>$out_order_id,
                                'userCode'=>'ZF441',
                            );

                            $tokenString='';
                            ksort($params);
                            foreach ($params as $k=>$v){
                                $tokenString.=$k.$v;
                            }
                            $token=strtoupper(md5($tokenString.'2022bsjZF441EYN'));

                            $params['token']=$token;
                            $params['devName']=$deviceName;
                            $params['money']=$money;
                            $params['broadCastType']=$broadCastType;
                            $params_string=self::allin_Params($params);
                            $url='https://ioe.car900.com/v1/openApi/dev/controlDevice.json?'.$params_string;
                            $res=self::curl_merch($url,'GET',json_encode($params),array('Content-Type: application/json'));
                            file_put_contents('yinxiang.log',var_export($out_order_id,true)."\r\n",FILE_APPEND);
                            file_put_contents('yinxiang.log',var_export($res,true)."\r\n",FILE_APPEND);
                        }
                        catch(TencentCloudSDKException $e) {
                            Log::info("云想印播报出错");
                            Log::info($e->getMessage().' | '.$e->getFile().' | '.$e->getLine());
                        }
                    }

                    if (is_object($v->device_type) && $v->device_type == "v_whty_1") {
                        $money = ($price / 100);
                        $broadcast_type = 1;
                        if ($type == '1') {
                            $broadcast_type = 2;
                        }
                        if ($type == '2') {
                            $broadcast_type = 3;
                        }
                        try {
                            $data = [
                                'accessKeyId' => 'IOT_ACCOUNT_PROD_tmBjvtahSEMDrRzhr',
                                'request_id' => uniqid(),
                                'biz_type' => '1',
                                'broadcast_type' => (string)$broadcast_type,
                                'money' => (string)$money,
                                'deviceId' => (string)$v->device_no,
                                'timestamp' => time() . '000'
                            ];
                            $sort = $data;
                            ksort($sort);
                            $signature = '';
                            foreach ($sort as $k => $v) {
                                if ("" != $v && "sign" != $k) {
                                    $signature .= $k . "=" . $v . "&";
                                }
                            }
                            $signature = substr($signature, 0, -1);
                            $sign = base64_encode(hash_hmac('sha256', $signature, 'GCAuGIKmHeROyrdVzNA9zTgbeo5dTYPkJ03B4gEagsC5fd2clVeWpp', true));
                            $data['sign'] = $sign;
                            $json = json_encode($data);
                            $curl = curl_init();
                            curl_setopt_array($curl, [
                                CURLOPT_TIMEOUT => 120,
                                CURLOPT_URL => 'https://voice.tysmartpos.com/api/dw/pushmsg',
                                CURLOPT_HEADER => false,
                                CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
                                CURLOPT_RETURNTRANSFER => true,
                                CURLOPT_SSL_VERIFYPEER => false,
                                CURLOPT_SSL_VERIFYHOST => false,
                                CURLOPT_POST => true,
                                CURLOPT_POSTFIELDS => $json,
                            ]);
                            $curlResponse = curl_exec($curl);
                            $curlCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
                            $curlMsg = curl_error($curl);
                            curl_close($curl);
                            if (!$curlResponse) {
                                throw new TencentCloudSDKException('curl请求失败：' . $curlMsg);
                            }
                        } catch (TencentCloudSDKException $e) {
                            Log::info("东莞云想印播报出错");
                            Log::info($e->getMessage() . ' | ' . $e->getFile() . ' | ' . $e->getLine());
                        }

                    }
                    
                    if ($v->device_type == "v_whty") {
                        $deviceName = $v->device_no;
                        $money = ($price / 100);
                        if ($type == '1') {
                            $content = '支付宝收款'.$money.'元';
                        }
                        if ($type == '2') {
                            $content = '微信收款'.$money.'元';
                        }
                        if ($type == '4') {
                            $content = '云闪付收款'.$money.'元';
                        }
                        try {
                             $post=array(
                                 'accessKeyId'=>'IOT_ACCOUNT_PROD_MTIzNDU2Nzg5MA',
                                 'requestId'=>$out_trade_no,
                                 'timestamp'=>time().'000',
                                 'deviceId'=>$v->device_no,
                                 'content'=>$content
                             );
                             ksort($post);
                             
                             $stringA=self::allin_Params($post);
                             $sign=base64_encode(hash_hmac('sha256', $stringA, 'cWF6c2RmcmU0NTZ5aHU3ODkwOWtmZ3J0c2ZmcjM0NDY1NDYzNDNkZ2ZnZmdmZXJlcg==',true));
                             $post['sign']=$sign;
                             $ch = curl_init();
                             file_put_contents('btianyu.log',var_export(json_encode($post),true)."\r\n",FILE_APPEND);
                             curl_setopt($ch, CURLOPT_URL, 'https://voice.tysmartpos.com/api/bank/pushmsg');
                             curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                             curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                                 'Content-Type: application/json'
                             ));
                             curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post));

                             $result = curl_exec($ch);
                             file_put_contents('btianyu.log',var_export($result,true)."\r\n",FILE_APPEND);
                             curl_close($ch);
                        }
                        catch(TencentCloudSDKException $e) {
                            Log::info("云想印播报出错");
                            Log::info($e->getMessage().' | '.$e->getFile().' | '.$e->getLine());
                        }
                    }
                    
                     //兴业银行云喇叭
                    if ($v->device_type == "v_ld_ns20") {
                        try {
                            if (!strpos($out_trade_no, 'scan')) {
                                $content = '';
                                $money = ($price / 100);
                                switch ($type) {
                                    case 1: $content = sprintf("支付宝收款 %s 元", $money); break;
                                    case 2: $content = sprintf("微信收款 %s 元", $money); break;
                                    case 3: $content = sprintf("京东收款 %s 元", $money); break;
                                    case 4: $content = sprintf("银联云闪付收款 %s 元", $money); break;
                                    default:

                                }
                                $landi = \App\Services\LandicorpService::getInstance();
                                $landi->params([
                                    'sn' => $v->device_no,
                                    'content' => $content,
                                ])->build($landi::PROD_URI.'/push');
                            }
                        }  catch(\Exception $e) {
                            error_log(date('Y-m-d H:i:s')." 【联迪云喇叭-error】： ".json_encode([$e->getMessage()])."\n\n", 3, "/tmp/". 'landi'.date('Ymd').".log");
                        }
                    }

                    //传盛语智云喇叭
                    if ($v->device_type == "csyz_YZ07") {
                        try {
                            if (!strpos($out_trade_no, 'scan')) {
                                $content = '';
                                $money = ($price / 100);
                                switch ($type) {
                                    case 1: $content = sprintf("支付宝收款 %s 元", $money); break;
                                    case 2: $content = sprintf("微信收款 %s 元", $money); break;
                                    case 3: $content = sprintf("京东收款 %s 元", $money); break;
                                    case 4: $content = sprintf("银联云闪付收款 %s 元", $money); break;
                                    default:

                                }
                                $yz = \App\Services\YzService::getInstance();
                                $yz->params([
                                    'deviceId' => $v->device_no,
                                    'content' => $content,
                                ])->build($yz::PROD_URI);
                            }
                        }  catch(\Exception $e) {
                            error_log(date('Y-m-d H:i:s')." 【传盛语智云喇叭-error】： ".json_encode([$e->getMessage()])."\n\n", 3, "/tmp/". 'csyz'.date('Ymd').".log");
                        }
                    }
                }
            }
        } catch (\Exception $ex) {
            \Illuminate\Support\Facades\Log::info('播报设备error');
            \Illuminate\Support\Facades\Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
        }
    }

    public static function curl_merch($url,$method,$params,$header = []){
        //初始化CURL句柄
        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER,1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if(!empty($header)){
            curl_setopt ( $curl, CURLOPT_HTTPHEADER, $header);
        }
        //请求时间
        $timeout = 30;
        curl_setopt ($curl, CURLOPT_CONNECTTIMEOUT, $timeout);
        switch ($method){
            case "GET" :
                curl_setopt($curl, CURLOPT_HTTPGET, true);
                break;
            case "POST":
                if(is_array($params)){
                    $params = json_encode($params,320);
                }

                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
                curl_setopt($curl, CURLOPT_POSTFIELDS,$params);
                break;
        }
        $data = curl_exec($curl);
        $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        curl_close($curl);//关闭cURL会话

        return $data;
    }

    public static function allin_Params(array $array){
        $buff = "";
        foreach ($array as $k => $v)
        {
            if($v != "" && !is_array($v)){
                $buff .= $k . "=" . $v . "&";
            }
        }

        $buff = trim($buff, "&");
        return $buff;
    }


    //mqtt推送
    public static function mqtt($device_id, $device_type, $message, $orderNum, $config_id, $type, $price)
    {
        try {
            $MqttConfig = MqttConfig::where('config_id', $config_id)->first();
            if (!$MqttConfig) {
                $MqttConfig = MqttConfig::where('config_id', '1234')->first();
            }

            if (!$MqttConfig) {
                return false;
            }
            $server = $MqttConfig->server;
            $port = $MqttConfig->port;
            $mq_group_id = $MqttConfig->group_id;
            $username = "Signature|" . $MqttConfig->access_key_id . "|" . $MqttConfig->instance_id . "";
            $str = '' . $MqttConfig->group_id . '@@@' . $device_id . '1' . '';
            $key = $MqttConfig->access_key_secret;
            $str = mb_convert_encoding($str, "UTF-8");
            $password = base64_encode(hash_hmac("sha1", $str, $key, true));

            $client_id = $mq_group_id . '@@@' . $device_id;
            $server_client_id = $mq_group_id . '@@@' . $device_id . '1';
            $topic = $MqttConfig->topic . "/p2p/" . $client_id;

            $content = json_encode([
                'message' => $message,
                'orderNum' => $orderNum,
                'type' => $type,//  1 支付宝 2 微信支付 3京东支付 4 银联闪付  5 积分抵扣  6.会员卡
                'price' => '' . $price . ''//分
            ]);

            $mqtt = new AliBaseController($server, $port, $server_client_id);
            if ($mqtt->connect(false, NULL, $username, $password)) {
                $mqtt->publish($topic, $content, 1);
                //$mqtt->close();
            } else {

            }
        } catch (\Exception $ex) {
            \Illuminate\Support\Facades\Log::info('mqtt推送errors');
            \Illuminate\Support\Facades\Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
        }
    }
    
    
    public static function addCoupon ($outTradeNo, $promotionDetail, $type)
    {
        try {
            error_log(date('Y-m-d H:i:s')." 【单品信息】： ".json_encode([$outTradeNo, $promotionDetail, $type])."\n\n", 3, "/tmp/". 'goodsInfo'.date('Ymd').".log");
            $coupon = [];
            $orderInfo = DB::table('orders')->where(['out_trade_no' => $outTradeNo])->select('company', 'store_id')->first();
            $storeInfo = DB::table('stores')->where(['store_id' => $orderInfo->store_id])->select('user_id', 'store_name', 'goods_cost', 'agent_cost')->first();

            $couponInfo = [];
            if (!empty($promotionDetail)) {
                if ($orderInfo->company == 'vbill') {
                    if (isset($promotionDetail['respData']['promotionDetail']) && !empty($promotionDetail['respData']['promotionDetail'])) {
                        $couponInfo = json_decode($promotionDetail['respData']['promotionDetail'], true);
                    }

                }
                if ($orderInfo->company == 'lianfu') {//工行
                    if (isset($promotionDetail['promotion_detail']) && !empty($promotionDetail['promotion_detail'])) {
                        $couponInfo = $promotionDetail['promotion_detail'];
                        foreach ($couponInfo as &$w) {
                            $w['goodsDetail'] = json_encode($w['goods_detail']);
                            $w['promotionId'] = $w['promotion_id'];
                            $w['amount'] = number_format($w['amount'] * 0.01, 2, '.', '');
                        }
                    }
                }
                if ($orderInfo->company == 'wftpay' || $orderInfo->company == 'cib' || $orderInfo->company == 'czbank') {
                    if (isset($promotionDetail['promotion_detail']) && !empty($promotionDetail['promotion_detail'])) {
                        $couponInfo = json_decode($promotionDetail['promotion_detail'], true)['promotion_detail'];
                        foreach ($couponInfo as &$w) {
                            $w['goodsDetail'] = json_encode($w['goods_detail']);
                            $w['promotionId'] = $w['promotion_id'];
                            $w['amount'] = number_format($w['amount'] * 0.01, 2, '.', '');
                        }
                    }

                }

                if ($orderInfo->company == 'lakala') {
                    if (isset($promotionDetail['promotionDetail']) && !empty($promotionDetail['promotionDetail'])) {
                        $couponInfo = json_decode($promotionDetail['promotionDetail'], true);
                        foreach ($couponInfo as &$w) {
                            $w['goodsDetail'] = json_encode($w['goodsDetail']);
                            $w['amount'] = number_format($w['amount'] * 0.01, 2, '.', '');
                        }
                    }
                }

                //建行
                if ($orderInfo->company == 'ccb') {
                    if (isset($promotionDetail['promotion_detail']) && !empty($promotionDetail['promotion_detail'])) {
                        $couponInfo = $promotionDetail['promotion_detail'];
                        foreach ($couponInfo as &$w) {
                            $w['goodsDetail'] = json_encode($w['goods_detail']);
                            $w['promotionId'] = $w['promotion_id'];
                            $w['amount'] = number_format($w['amount'] * 0.01, 2, '.', '');
                        }
                    }

                }

                if ($orderInfo->company == 'cmbcunion') {
                    $couponInfo = json_decode($promotionDetail, true);
                    foreach ($couponInfo as &$w) {
                        $w['goodsDetail'] = json_encode($w['goodsDetails']);
                        $w['amount'] = number_format($w['amount'] * 0.01, 2, '.', '');
                    }
                }
                if ($orderInfo->company == 'gtxy'  || $orderInfo->company == 'gtxy_v2') {
                    if(is_array($promotionDetail)){
                        $couponInfo=$promotionDetail;
                    }else{
                        $couponInfo = json_decode($promotionDetail, true);
                    }
                    foreach ($couponInfo as &$w) {
                        $w['goodsDetail'] = json_encode($w['goods_detail']??[]);
                        $w['promotionId'] = $w['promotion_id']??"";
                        $w['amount'] = number_format($w['amount'] * 0.01, 2, '.', '');
                    }
                }

                if ($orderInfo->company == 'leshuaunion' ) {
                    if(is_array($promotionDetail)){
                        $couponInfo=$promotionDetail;
                    }else{
                        $couponInfo = json_decode($promotionDetail, true);
                    }
                    foreach ($couponInfo as &$w) {
                        $w['goodsDetail'] = json_encode($w['goods_detail']??[]);
                        $w['promotionId'] = $w['promotion_id']??"";
                        $w['amount'] = number_format($w['amount'] * 0.01, 2, '.', '');
                    }
                }

            }

            if ($type == 'pay') { //支付
                foreach ($couponInfo as $v) {
                    $coupon[] = [
                        'out_trade_no'  => $outTradeNo,
                        'store_id'      => $orderInfo->store_id,
                        'user_id'       => $storeInfo->user_id,
                        'coupon_type'   => $v['type'],
                        'goods_detail'  => $v['goodsDetail'],
                        'coupon_name'   => $v['name'],
                        'promotion_id'  => $v['promotionId'],
                        'coupon_amount' => $v['amount'],
                        'created_at'    => date('Y-m-d H:i:s'),
                        'company'       => $orderInfo->company,
                        'store_name'    => $storeInfo->store_name,
                        'num'           => 1,
                        'cost'          => $storeInfo->goods_cost,
                        'agent_cost'    => $storeInfo->agent_cost,
                    ];
                }
                if (!empty($coupon)) {
                     //扣除服务费
                    $goods_cost = $storeInfo->goods_cost * count($coupon);
                    DB::table('stores')->where('store_id' , $orderInfo->store_id)->decrement('goods_cost_balance', $goods_cost);
                    DB::table('order_goods_details')->insert($coupon);
                }
            }
            if ($type == 'query') { //查询
                if (!DB::table('order_goods_details')->where(['out_trade_no' => $outTradeNo])->first()) {
                    foreach ($couponInfo as $v) {
                        $coupon[] = [
                            'out_trade_no'  => $outTradeNo,
                            'store_id'      => $orderInfo->store_id,
                            'user_id'       => $storeInfo->user_id,
                            'coupon_type'   => $v['type'],
                            'goods_detail'  => $v['goodsDetail'],
                            'coupon_name'   => $v['name'],
                            'promotion_id'  => $v['promotionId'],
                            'coupon_amount' => $v['amount'],
                            'created_at'    => date('Y-m-d H:i:s'),
                            'company'       => $orderInfo->company,
                            'store_name'    => $storeInfo->store_name,
                            'num'           => 1,
                            'cost'          => $storeInfo->goods_cost,
                            'agent_cost'    => $storeInfo->agent_cost,
                        ];
                    }
                    if (!empty($coupon)) {
                        $goods_cost = $storeInfo->goods_cost * count($coupon);
                        DB::table('stores')->where('store_id' , $orderInfo->store_id)->decrement('goods_cost_balance', $goods_cost);
                        DB::table('order_goods_details')->insert($coupon);
                    }
                }
            }
            if ($type == 'refund') { //退款
                DB::table('order_goods_details')->where(['out_trade_no' => $outTradeNo])->update(['status' => 2]);
                $goods_cost = DB::table('order_goods_details')->where(['out_trade_no' => $outTradeNo])->sum('cost');
                DB::table('stores')->where('store_id' , $orderInfo->store_id)->increment('goods_cost_balance', $goods_cost);
            }
        } catch (\Exception $ex) {
            error_log(date('Y-m-d H:i:s')." 【单品信息异常】： ".json_encode([$ex->getLine(), $ex->getMessage(), $outTradeNo, $type])."\n\n", 3, "/tmp/". 'goodsInfoError'.date('Ymd').".log");
        }
    }


}

